package logic

import (
	"context"
	"errors"
	"goods-master/cache"
	"goods-master/pkg"
	"math/rand"
	"strconv"
	"time"

	"goods-master/goodsrpc/goodsrpc"
	"goods-master/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SandSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSandSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SandSmsLogic {
	return &SandSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证码
func (l *SandSmsLogic) SandSms(in *goodsrpc.SandSmsRequest) (*goodsrpc.SandSmsResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sandsmsnumber"+in.Mobile).Int()
	if result >= 1 {
		return nil, errors.New("一分钟之内只能发送一次验证码")
	}
	code := rand.Intn(9000) + 1000
	sand, _ := pkg.Sand(in.Mobile, strconv.Itoa(code))
	if sand.Code != 2 {
		return nil, errors.New("验证码发送失败")
	}
	cache.Rdb.Set(l.ctx, "sandsms"+in.Mobile, code, time.Minute*3)
	cache.Rdb.Set(l.ctx, "sandsmsnumber"+in.Mobile, code, time.Minute*1)
	return &goodsrpc.SandSmsResponse{}, nil
}
